#region Using

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;

using Gizmox.WebGUI.Forms;
using QueryBuilder;
//using DashboardQD.AppConfig;
//using Excel = Microsoft.Office.Interop.Excel;

#endregion

namespace TVC.Modules.Ddb
{
    public partial class frmQDAddinDrilldown : Form
    {
        private SQLBuilder _sqlBuilder;
        TreeNode _ANode = null;
        //bool flag_view = false;
        //String sErr = "";
        //string idHandler = "";
        //String _ttFormular = "";
        //String _status = "F";
        public DataTable _dataTable = new DataTable();
        //Node[] _arrNodes = null;
        //QDConfig _config;
        readonly Object _xlsApp;

        //public QDConfig Config
        //{
        //    get { return _config; }
        //    set
        //    {
        //        _config = value;
        //        BUS.LIST_QD_SCHEMAControl schCtr = new LIST_QD_SCHEMAControl();

        //        DTO.LIST_QD_SCHEMAInfo schInf = schCtr.Get(_sqlBuilder.Database, _sqlBuilder.Table, ref sErr);
        //        string keyconn = schInf.DEFAULT_CONN;
        //        string connectstring = _config.GetConnection(ref keyconn, "AP");
        //        _sqlBuilder.ConnID = keyconn;
        //        _sqlBuilder.StrConnectDes = connectstring;
        //        //_strConnectDes = connectstring;
        //    }
        //}

        public frmQDAddinDrilldown()
        {
            InitializeComponent();
        }

        public frmQDAddinDrilldown(string connectDesc)
        {
            InitializeComponent();
            //_strConnectDes = connectDesc;
            _sqlBuilder = new SQLBuilder(processingMode.Balance);
            _sqlBuilder.StrConnectDes = connectDesc;
            //TopMost = true;
            //ThemeResolutionService.ApplyThemeToControlTree(this, THEME);
        }

        public frmQDAddinDrilldown(string Pos, string formular, string connectDesc)
        {
            InitializeComponent();
            //_strConnectDes = connectDesc;
            Init(Pos, formular);
            _sqlBuilder.StrConnectDes = connectDesc;
            //ThemeResolutionService.ApplyThemeToControlTree(this, THEME);

        }
        public frmQDAddinDrilldown(string Pos, SQLBuilder sqBuilder)
        {
            InitializeComponent();
            Init(Pos, sqBuilder);
            //_strConnectDes = sqBuilder.StrConnectDes;
            //ThemeResolutionService.ApplyThemeToControlTree(this, THEME);

        }
        public frmQDAddinDrilldown(Gizmox.WebGUI.Common.Interfaces.IContext objContext)
            : base(objContext)
        {
            
        }


        public void Init(string Pos, SQLBuilder sqBuilder)
        {
            _sqlBuilder = new SQLBuilder(sqBuilder);
            //((GridViewComboBoxColumn)dgvSelectNodes.Columns["Agregate"]).DataSource = Parsing.GetListNumberAgregate();
            _sqlBuilder.Pos = Pos;
            //_xlsApp = xls;
            //TopMost = true;
            //GetQueryBuilderFromFomular(formular);
        }

        public void Init(string Pos, string formular)
        {
            _sqlBuilder = new SQLBuilder(processingMode.Balance);
            //((GridViewComboBoxColumn)dgvSelectNodes.Columns["Agregate"]).DataSource = Parsing.GetListNumberAgregate();
            _sqlBuilder.Pos = Pos;
            //_xlsApp = xls;
            //TopMost = true;
            GetQueryBuilderFromFomular(formular);
            //if (xls == null)
            //    btPivotTable.Visible = false;
        }

        public void GetQueryBuilderFromFomular(string formular)
        {
            if (formular.Contains("TT_XLB_EB"))//|| formular.Contains("USER TABLE")
            {
                if (_xlsApp != null)
                {
                    //Excel._Worksheet sheet = (Excel._Worksheet)_xlsApp.ActiveWorkbook.ActiveSheet;
                    //Excel._Workbook wbook = (Excel._Workbook)_xlsApp.ActiveWorkbook;

                    //string vParamsString = Regex.Match(formular, @"\" + System.Convert.ToChar(34) + @"\,.+?\)").Value.ToString();// TRANSINFO: .NET Equivalent of Microsoft.VisualBasic NameSpace 

                    //// fill to parameter Array
                    //int i = 0, n = 0;

                    //if (!(string.IsNullOrEmpty(vParamsString)))
                    //{
                    //    vParamsString = vParamsString.Substring(1);// TRANSINFO: .NET Equivalent of Microsoft.VisualBasic NameSpace 
                    //    vParamsString = vParamsString.Substring(1, vParamsString.Length - 2);// Strings.Mid(vParamsString, 1,  /* TRANSINFO: .NET Equivalent of Microsoft.VisualBasic NameSpace */ vParamsString.Length - 1); 
                    //    vParamsString = vParamsString + ","; //  them dau , cho de xu ly
                    //    n = Regex.Matches(vParamsString, ".*?,").Count; //  cac tham so
                    //    if (n > 0)
                    //    {
                    //        string[] vParameter = new string[n]; // tham so dau tien la vi tri cua cong thuc
                    //        foreach (System.Text.RegularExpressions.Match p in Regex.Matches(vParamsString, ".*?,"))
                    //        {
                    //            i = i + 1;
                    //            if (i == 1)
                    //            {
                    //                _sqlBuilder.Pos = p.Value.ToString().Replace(",", string.Empty);

                    //            }
                    //            else
                    //            {

                    //                string address = p.Value.ToString().Replace(",", string.Empty);
                    //                string value = "";
                    //                //try
                    //                //{
                    //                //    value = sheet.get_Range(address, Type.Missing).get_Value(Type.Missing).ToString();

                    //                //    _sqlBuilder.ParaValueList[i - 1] = value;
                    //                foreach (Excel._Worksheet isheet in wbook.Sheets)
                    //                {
                    //                    try
                    //                    {
                    //                        value = isheet.get_Range(address, Type.Missing).get_Value(Type.Missing).ToString();

                    //                        _sqlBuilder.ParaValueList[i - 1] = value;
                    //                        break;

                    //                    }
                    //                    catch
                    //                    {
                    //                    }
                    //                }

                    //                //}
                    //                //catch
                    //                //{
                    //                //    value = ((Excel.Range)wbook.Sheets.get_Item(address)).get_Value(Type.Missing).ToString();

                    //                //    _sqlBuilder.ParaValueList[i - 1] = value;
                    //                //}
                    //                //vParameter[i - 1] = p.Value.ToString().Replace(",", string.Empty);
                    //            }

                    //        }
                    //    }
                    //}
                }
                Parsing.Formular2SQLBuilder(formular, ref _sqlBuilder);



                //SetDataToForm();
            }
            else if (formular.Contains("TVC_QUERY"))
            { Parsing.TVCFormular2SQLBuilder(formular, ref _sqlBuilder); }
        }

        private static void TView_DragDrop(object sender, DragEventArgs e)
        {

        }



       

        private void frmQDAddinDrilldown_Load(object sender, EventArgs e)
        {
            try
            {
                //      dgvResult.AllowDrop = true;

                //        DialogResult = DialogResult.Yes;
                BindingList<Node> list = SchemaDefinition.GetDecorateTableByCode(_sqlBuilder.Table, _sqlBuilder.Database);
                //twSchema = RadTreeViewLoader.LoadTree(ref twSchema, list, _sqlBuilder.Table, "");
                TView = TreeViewLoader.LoadTree(ref TView, list, _sqlBuilder.Table, "");
                for (int i = 0; i < TView.Nodes.Count; i++)
                {
                    TView.Nodes[i].DragTargets = new Gizmox.WebGUI.Forms.Component[] { TView, dgridView };

                }
                //BUS.LIST_QD_SCHEMAControl ctr = new LIST_QD_SCHEMAControl();
                //DTO.LIST_QD_SCHEMAInfo inf = ctr.Get(_sqlBuilder.Database, _sqlBuilder.Table, ref sErr);
                //string key = inf.DEFAULT_CONN;
                //_strConnectDes = _sqlBuilder.StrConnectDes = _config.GetConnection(ref key, "AP");
                //       myRadGrid12.GroupingEnabled = true;

                LoadDataGrid();
            }
            catch (Exception ex) { lbErr.Text = ex.Message; }
        }

        private static void Formatgridview(ref DataGridView dg, DataTable dt)
        {
            foreach (DataColumn col in dt.Columns)
            {
                if (col.DataType == typeof(Int32) || col.DataType == typeof(Double) || col.DataType == typeof(float))
                {
                    dg.Columns[col.ColumnName].DefaultCellStyle.Format = "N2";
                }
                else if (col.DataType == typeof(DateTime))
                {
                    dg.Columns[col.ColumnName].DefaultCellStyle.Format = "dd/MM/yyyy";
                }
            }
        }
        private void LoadDataGrid()
        {
            BUS.CommonControl commo = new BUS.CommonControl();
            DataTable dt = _sqlBuilder.BuildDataTable("");
            dgridView.AutoGenerateColumns = true;
            //dgridView.ShowGroupingDropArea = true;
            bisData.DataSource = dt;

            Formatgridview(ref dgridView, dt);
            //myRadGrid12.DataSource = dt;
            //myRadGrid12.DataBind();
            //Radgridview.DataSource = dt;
            //Radgridview.DataBind();
            //      dgridView.RetrieveStructure();
            //      dgvResult.AllowEdit = Janus.Windows.GridEX.InheritableBoolean.False;
            //     dgridView.AutoSizeColumns();
            //for (int j = 0; j < _sqlBuilder.SelectedNodes.Count; j++)
            //{
            //    //if (dgvResult.RootTable.Columns.Contains(_sqlBuilder.SelectedNodes[j].MyCode))
            //    //    dgvResult.RootTable.Columns[_sqlBuilder.SelectedNodes[j].MyCode].Caption = _sqlBuilder.SelectedNodes[j].Description;

            //    if (_sqlBuilder.SelectedNodes[j].Agregate != "")
            //    {
            //        if (dgridView.RootTable.Columns.Contains(_sqlBuilder.SelectedNodes[j].MyCode))
            //        {
            //            switch (_sqlBuilder.SelectedNodes[j].Agregate)
            //            {
            //                case "SUM":
            //                    dgvResult.RootTable.Columns[_sqlBuilder.SelectedNodes[j].MyCode].AggregateFunction = Janus.Windows.GridEX.AggregateFunction.Sum;
            //                    break;
            //                case "COUNT":
            //                    dgvResult.RootTable.Columns[_sqlBuilder.SelectedNodes[j].MyCode].AggregateFunction = Janus.Windows.GridEX.AggregateFunction.Count;
            //                    break;
            //                case "AVG":
            //                    dgvResult.RootTable.Columns[_sqlBuilder.SelectedNodes[j].MyCode].AggregateFunction = Janus.Windows.GridEX.AggregateFunction.Average;
            //                    break;
            //                case "MAX":
            //                    dgvResult.RootTable.Columns[_sqlBuilder.SelectedNodes[j].MyCode].AggregateFunction = Janus.Windows.GridEX.AggregateFunction.Max;
            //                    break;
            //                case "MIN":
            //                    dgvResult.RootTable.Columns[_sqlBuilder.SelectedNodes[j].MyCode].AggregateFunction = Janus.Windows.GridEX.AggregateFunction.Min;
            //                    break;
            //            }

            //        }
            //    }
            //}
            //for (int i = 0; i < dgvResult.RootTable.Columns.Count; i++)
            //{
            //    //dgvResult.RootTable.Columns[i].AutoSizeMode = Janus.Windows.GridEX.ColumnAutoSizeMode.DisplayedCellsAndHeader;
            //    if (dgvResult.RootTable.Columns[i].DataTypeCode == TypeCode.Decimal || dgvResult.RootTable.Columns[i].DataTypeCode == TypeCode.Double)
            //    {
            //        dgvResult.RootTable.Columns[i].FormatString = dgvResult.RootTable.Columns[i].TotalFormatString = "###,###.##";
            //        dgvResult.RootTable.Columns[i].TotalFormatString = "###,###.##";
            //    }
            //    // dgvResult.Columns[i].A
            //}

            //dgvResult.RootTable.GroupTotals = GroupTotals.Always;
            //dgvResult.RootTable.TotalRow = InheritableBoolean.True;

        }

        

        private void dgridView_DragDrop(object sender, DragEventArgs e)
        {
            //if (e is DragDropEventArgs)
            //{
            //    DragDropEventArgs objDragDropEventArgs = e as DragDropEventArgs;
            //    if (objDragDropEventArgs != null)
            //    {
            //        if (objDragDropEventArgs.Source is TreeNode
            //                )
            //        {
            if (_ANode != null)
            {
                bool flag = true;
                //Node a = new Node(((TreeNode)objDragDropEventArgs.Source).Name, ((TreeNode)objDragDropEventArgs.Source).Text);
                Node a = new Node(_ANode.Name, _ANode.Text);
                for (int i = 0; i < _sqlBuilder.SelectedNodes.Count; i++)
                    if (_sqlBuilder.SelectedNodes[i].Code == a.Code)
                    {
                        flag = false;
                        break;
                    }
                if (flag)
                {

                    _sqlBuilder.SelectedNodes.Add(a);
                    LoadDataGrid();
                }
            }
            //        }
            //    }
            //}
        }

       
        private void TView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            _ANode = e.Node;
        }
    }
}